package io.bdmc.modules.bss.controller;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import io.bdmc.common.annotation.SysLogger;
import io.bdmc.common.utils.Constant;
import io.bdmc.common.utils.ExcelImport;
import io.bdmc.common.utils.MyMap;
import io.bdmc.common.utils.MyPage;
import io.bdmc.common.utils.R;
import io.bdmc.common.validator.ValidatorUtils;
import io.bdmc.common.validator.group.AddGroup;
import io.bdmc.common.validator.group.UpdateGroup;
import io.bdmc.modules.bss.entity.SmkDevice;
import io.bdmc.modules.bss.entity.SmkShop;
import io.bdmc.modules.bss.model.LabelValue;
import io.bdmc.modules.bss.model.ShopParam;
import io.bdmc.modules.bss.service.ISmkDeviceService;
import io.bdmc.modules.bss.service.ISmkShopService;
import io.bdmc.modules.sys.controller.AbstractController;
import io.bdmc.modules.sys.entity.SysDept;
import io.bdmc.modules.sys.service.ISysDeptService;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author huang lu
 * @since 2019-01-21
 */
@RestController
@RequestMapping("/bss/shop")

public class SmkShopController extends AbstractController {
	@Autowired
	private ISmkShopService _shopSvs;

	@Autowired
	private ISysDeptService _deptSvs;

	@Autowired
	private ISmkDeviceService _devSvs;

	@RequestMapping("/list")
	@RequiresPermissions("bss:shop:list")
	public R list(ShopParam params) {
		MyPage<SmkShop> myPage = new MyPage<SmkShop>(params.getCurrent(), params.getSize());
		MyPage<SmkShop> map = _shopSvs.mySelectPage(myPage, params);
		return R.ok().putData(MyMap.ok(map.getRecords(), map.getTotal()));

	}

	@RequestMapping("/listbydept")
	@RequiresPermissions("bss:shop:list")
	public R listByDeptId(Long deptId) {
		if (deptId < 0)
			return R.error("参数错误。");
		ShopParam sp = new ShopParam(1, 1000, "", deptId);
		MyPage<SmkShop> myPage = new MyPage<SmkShop>(sp.getCurrent(), sp.getSize());
		List<LabelValue> list = _shopSvs.mySelectByDept(myPage, sp);
		return R.ok().putData(list);
	}

	/**
	 * 保存店铺
	 */
	@SysLogger("保存店铺")
	@RequestMapping("/save")
	@RequiresPermissions("bss:shop:save")
	public R save(@RequestBody SmkShop shop) {
		ValidatorUtils.validateEntity(shop, AddGroup.class);
		shop.setJoinBy(getUserId());
		shop.setJoinDate(LocalDateTime.now());
		Boolean b = shop.insert();
		return R.trueOfFalse(b);
	}

	/**
	 * 修改店铺
	 */
	@SysLogger("修改店铺")
	@RequestMapping("/update")
	@RequiresPermissions("bss:shop:update")
	public R update(@RequestBody SmkShop shop) {
		ValidatorUtils.validateEntity(shop, UpdateGroup.class);
		SmkShop dbShop = _shopSvs.getById(shop.getShopId());
		Boolean b = false;
		if (dbShop.getDeptId() != shop.getDeptId()) {// 需更新绑定设备的部门
			QueryWrapper<SmkDevice> w1 = new QueryWrapper<>();
			w1.eq("shop_id", shop.getShopId());
			List<SmkDevice> devs = _devSvs.list(w1);
			if (devs.size() > 0) {
				b = _shopSvs.updateShopAndDevDept(shop, devs);
			}
		}
		b = shop.updateById();
		return R.trueOfFalse(b);
	}

	/**
	 * 删除
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("bss:shop:delete")
	public R delete(@RequestBody long shopId) {
		if (shopId > 0)
			_shopSvs.removeById(shopId);
		return R.ok();
	}

	@RequestMapping(value = "export")
	@RequiresPermissions("bss:shop:export")
	public R downloadAllClassmate(ShopParam params) throws IOException {
		MyPage<SmkShop> myPage = new MyPage<SmkShop>(1, 10000000);
		MyPage<SmkShop> map = _shopSvs.mySelectPage(myPage, params);
		List<SmkShop> data = map.getRecords();
		if (data.size() == 0) {
			return R.error(-1, "查询数据为空，请更改查询条件！");
		}
		HSSFWorkbook workbook = new HSSFWorkbook();
		HSSFSheet sheet = workbook.createSheet("设备列表");
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
		String dateString = LocalDateTime.now().format(formatter);
		String fileName = "商铺列表" + dateString + ".xls";// 设置要导出的文件的名字
		// 新增数据行，并且设置单元格数据
		int rowNum = 1;
		String[] headers = { "序号", "店铺名称", "所属场所", "所属部门", "店铺地址", "设备数量", "联系人", "联系电话", "微信名称", "纬度", "经度", "紧急联系人",
				"店铺照片", "责任书" };
		// headers表示excel表中第一行的表头
		HSSFRow row = sheet.createRow(0);
		// 在excel表中添加表头
		for (int i = 0; i < headers.length; i++) {
			HSSFCell cell = row.createCell(i);
			HSSFRichTextString text = new HSSFRichTextString(headers[i]);
			cell.setCellValue(text);
		}

		// 在表中存放查询到的数据放入对应的列
		for (SmkShop d : data) {
			HSSFRow row1 = sheet.createRow(rowNum);
			row1.createCell(0).setCellValue(rowNum);
			row1.createCell(1).setCellValue(d.getShopName() != null ? d.getShopName() : "");
			row1.createCell(2)
					.setCellValue(d.getShopPlace() != null ? Constant.formateShopPlace(d.getShopPlace()) : "");
			row1.createCell(3).setCellValue(d.getDepName() != null ? d.getDepName() : "");
			row1.createCell(4).setCellValue(d.getAddr() != null ? d.getAddr() : "");
			row1.createCell(5).setCellValue(d.getDevCount() != null ? d.getDevCount() : "");
			row1.createCell(6).setCellValue(d.getManagerName() != null ? d.getManagerName() : "");
			row1.createCell(7).setCellValue(d.getManagerMobile() != null ? d.getManagerMobile() : "");
			row1.createCell(8).setCellValue(d.getWxName() != null ? d.getWxName() : "");
			row1.createCell(9).setCellValue(d.getLat() != null ? d.getLat() : "");
			row1.createCell(10).setCellValue(d.getLng() != null ? d.getLng() : "");
			row1.createCell(11).setCellValue(d.getAlarmNotifier() != null ? d.getAlarmNotifier() : "");
			row1.createCell(12).setCellValue(d.getPicture() != null ? d.getPicture() : "");
			row1.createCell(13).setCellValue(d.getDutyLetter() != null ? d.getDutyLetter() : "");
			rowNum++;
		}
		try {
			File path = new File(Constant.EXPORTPATH);
			if (!path.exists()) {
				path.mkdir();
			}
			File f = new File(path.getAbsolutePath() + "/excel/", fileName);
			if (!f.getParentFile().exists()) {
				f.getParentFile().mkdir();
			}
			FileOutputStream fileOutputStream = new FileOutputStream(f);// 指定路径与名字和格式
			workbook.write(fileOutputStream);// 将数据写出去
			fileOutputStream.close();// 关闭输出流
			return R.ok().putData("/excel/" + fileName);
		} catch (Exception e) {
			e.printStackTrace();
			return R.error(-1, e.getMessage());
		}
	}

	@RequestMapping("import")
	@RequiresPermissions("bss:shop:import")
	// @ApiOperation(value = "导入Excel",notes = "将数据以Excel的形式导入到数据库中")
	public R importExcel(@RequestParam("file") MultipartFile file) throws Exception {
		// 获取用户上传表格的地址，执行完程序后表格将会删除，避免占用内存
		// 根据地址和文件名准确获取用户上传的表格
		// File tempFile = new File(file.getInputStream());
		try {
			// 将MultipartFile转换为File类型
			// file.transferTo(tempFile);
			String fileName = file.getOriginalFilename();
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
			InputStream in = file.getInputStream();
			List<Map<String, String>> dataList = ExcelImport.read(in, suffix);

			String deptName = dataList.get(0).get("所属部门").toString();
			List<SmkShop> list = new ArrayList<SmkShop>();
			QueryWrapper<SysDept> w1 = new QueryWrapper<>();
			w1.eq("name", deptName);
			SysDept dept = _deptSvs.getOne(w1);
			if (dept == null) {
				return R.error("部门数据未找到");
			}
			for (int i = 0; i < dataList.size(); i++) {
				String shopName = dataList.get(i).get("场所名称").toString();
				String shopAddr = dataList.get(i).get("场所地址").toString();
				String managerName = dataList.get(i).get("联系人").toString();
				String managerMobile = dataList.get(i).get("联系电话").toString();
				String shopPlaceName = dataList.get(i).get("场所类型").toString();
				SmkShop s = new SmkShop();
				s.setAddr(shopAddr);
				s.setShopName(shopName);
				s.setManagerMobile(managerMobile);
				s.setManagerName(managerName);
				s.setDeptId(dept.getDeptId());
				s.setJoinDate(LocalDateTime.now());
				s.setJoinBy(getUserId());
				s.setShopPlace(Constant.getShopPlaceFromStr(shopPlaceName));
				list.add(s);
			}
			Boolean re = _shopSvs.saveBatch(list);
			// 加入实时表
			return R.trueOfFalse(re);
		} catch (Exception e) {
			// tempFile.delete();
			// throw new Exception("批量录入用户失败，请检查表格中的数据是否和数据库中的数据冲突！");
			return R.error("导入失败，请检查表格中的数据");
		}
	}

	@RequestMapping("shop_map")
	public R shopMap(@RequestParam("file") MultipartFile file, @RequestParam Long shopId) throws Exception {
		File targetFile = null;
		String fileName = file.getOriginalFilename();// 获取文件名加后缀
		if (fileName != null && fileName != "") {
			SmkShop s = _shopSvs.getById(shopId);
			fileName = s.getShopName() + fileName;
			File path = new File(Constant.EXPORTPATH);
			if (!path.exists()) {
				path.mkdir();
			}
			// 生成jpg图片
			String savePath = path.getAbsolutePath() + "/image/";// 新生成的图片
			File path1 = new File(savePath);
			if (!path1.exists()) {
				path1.mkdir();
			}
			targetFile = new File(path1, fileName);
			String serverPath = "/image/" +fileName;
			try {
				// 将上传的文件写到服务器上指定的文件。
				file.transferTo(targetFile);
				s.setShopMap(serverPath);
				s.updateById();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return R.ok().putData(serverPath);
		}else{
			return R.error(-1,"请上传图片文件");
		}
	}

	@RequestMapping("download")
	// @RequiresPermissions("bss:shop:import")
	// @ApiOperation(value = "导入Excel",notes = "将数据以Excel的形式导入到数据库中")
	public R downloadPic(@RequestParam("file") MultipartFile file) throws Exception {
		// 获取用户上传表格的地址，执行完程序后表格将会删除，避免占用内存
		// 根据地址和文件名准确获取用户上传的表格
		// File tempFile = new File(file.getInputStream());
		try {
			// 将MultipartFile转换为File类型
			// file.transferTo(tempFile);
			String fileName = file.getOriginalFilename();
			String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
			InputStream in = file.getInputStream();
			List<Map<String, String>> dataList = ExcelImport.read(in, suffix);

			for (int i = 0; i < dataList.size(); i++) {
				String duty = dataList.get(i).get("duty_letter");
				String picture = dataList.get(i).get("picture");
				if (!StringUtils.isEmpty(duty)) {
					String url = "http://xf.ctjt.cn:8090/smokev2" + duty;
					String newfileName = "d:/test/" + dataList.get(i).get("shop_name") + ".jpg";
					downloadPicture(url, newfileName);
				}
				if (!StringUtils.isEmpty(picture)) {
					String url = "http://xf.ctjt.cn:8090/smokev2" + picture;
					String newfileName = "d:/test/" + dataList.get(i).get("shop_name") + dataList.get(i).get("imei")
							+ ".jpg";
					;
					downloadPicture(url, newfileName);
				}
			}

			// 加入实时表
			return R.ok();
		} catch (Exception e) {
			// tempFile.delete();
			// throw new Exception("批量录入用户失败，请检查表格中的数据是否和数据库中的数据冲突！");
			e.printStackTrace();
			return R.error("导入失败，请检查表格中的数据");
		}
	}

	// @RequestMapping("/latlng")
	// @RequiresPermissions("bss:shop:delete")
	// public R latlng() {
	// 	MyPage<SmkShop> myPage = new MyPage<SmkShop>(1, 10000000);
	// 	MyPage<SmkShop> map = _shopSvs.mySelectPage(myPage, new ShopParam(1L, 100000L, "", 1L));
	// 	List<SmkShop> data = map.getRecords();
	// 	List<SmkShop> entitys = new ArrayList<>();
	// 	for (SmkShop s : data) {
	// 		if(StringUtils.isEmpty(s.getLat())||StringUtils.isEmpty(s.getLng())){
	// 			 continue;
	// 		}
	// 	   double lat = Double.parseDouble(s.getLat());
	// 	   double lng = Double.parseDouble(s.getLng());
	// 	   double[] latlng =  CoordTransform.transformWGS84ToGCJ02(lng,lat);
	// 	   s.setLng(String.valueOf(latlng[0]));
	// 	   s.setLat(String.valueOf(latlng[1]));
	// 	   entitys.add(s);
		 
	// 	}
	// 	boolean b = _shopSvs.updateBatchById(entitys);
	// 	return R.trueOfFalse(b);
	// }

	private void downloadPicture(String urlList, String imageName) {
		URL url = null;
		try {
			url = new URL(urlList);
			DataInputStream dataInputStream = new DataInputStream(url.openStream());
			File f = new File(imageName);
			if (!f.exists()) {
				f.createNewFile();
			}
			FileOutputStream fileOutputStream = new FileOutputStream(f);
			ByteArrayOutputStream output = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int length;
			while ((length = dataInputStream.read(buffer)) > 0) {
				output.write(buffer, 0, length);
			}
			byte[] context = output.toByteArray();
			fileOutputStream.write(context);
			dataInputStream.close();
			fileOutputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
